/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentFieldValue;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.ContentFieldValue;
import com.blandware.atleap.model.core.ContentLocale;
import com.blandware.atleap.service.core.ContentFieldManager;
import com.blandware.atleap.service.core.ContentLocaleManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentFieldValueForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * <p>Exposes requested ContentFieldValue bean to request to view its properties on JSP page
 * </p>
 * <p><a href="ViewContentFieldValueAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.28 $ $Date: 2006/08/03 10:07:50 $
 * @struts.action path="/core/contentFieldValue/view"
 * name="contentFieldValueForm"
 * scope="request"
 * validate="false"
 * roles="core-contentFieldValue-view"
 * @struts.action-forward name="viewContentFieldValue"
 * path=".core.contentFieldValue.view"
 * @struts.action-forward name="listContentFieldValues"
 * path="/core/contentFieldValue/list.do"
 * redirect="false"
 */
public final class ViewContentFieldValueAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        String redirectUrl = request.getParameter("redirectUrl");
        if (!GenericValidator.isBlankOrNull(redirectUrl)) {
            request.getSession().setAttribute(WebappConstants.REDIRECT_URL_KEY, redirectUrl);
        }

		ContentFieldValueForm contentFieldValueForm = (ContentFieldValueForm) form;
		Long contentFieldId = null;
		if ( !GenericValidator.isBlankOrNull(contentFieldValueForm.getContentFieldId()) ) {
			contentFieldId = Long.valueOf(contentFieldValueForm.getContentFieldId());
		} else if ( request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY) != null ) {
			contentFieldId = (Long) request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing content field ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.CONTENT_FIELD_ID_KEY, contentFieldId);

		List cfvLocales = null;

		if ( request.getAttribute(WebappConstants.CONTENT_FIELD_VALUE_SELECTED_LOCALES_KEY) != null ) {
			cfvLocales = (List) request.getAttribute(WebappConstants.CONTENT_FIELD_VALUE_SELECTED_LOCALES_KEY);
		} else if ( !GenericValidator.isBlankOrNull(request.getParameter("locale")) ) {
			String locale = request.getParameter("locale");
			cfvLocales = new ArrayList();
			cfvLocales.add(locale);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing content field value locale. Returning to list...");
			}
			return mapping.findForward("listContentFieldValues");
		}

		ContentFieldManager contentFieldManager = (ContentFieldManager) getBean(Constants.CONTENT_FIELD_MANAGER_BEAN);
		ContentLocaleManager contentLocaleManager = (ContentLocaleManager) getBean(Constants.CONTENT_LOCALE_MANAGER_BEAN);

		// export content field to session
		ContentField contentField = contentFieldManager.retrieveContentField(contentFieldId);
		request.getSession().setAttribute(WebappConstants.CONTENT_FIELD_KEY, contentField);

		SortedMap contentFieldValues = new TreeMap();

		// we need string representations of our BLOB values, so create one more map
		SortedMap values = new TreeMap();

		for ( int i = 0; i < cfvLocales.size(); i++ ) {
			String localeIdentifier = (String) cfvLocales.get(i);
			ContentLocale locale = contentLocaleManager.retrieveContentLocale(localeIdentifier);
			if ( locale != null ) {
				ContentFieldValue contentFieldValue = contentFieldManager.findContentFieldValueByContentFieldIdAndLocale(contentFieldId, localeIdentifier);
				if ( contentFieldValue != null ) {
					contentFieldValues.put(locale, contentFieldValue);
					if ( contentFieldValue.getContentField().getType() == ContentField.LINE_TYPE || contentFieldValue.getContentField().getType() == ContentField.MULTILINE_TYPE ) {
						String value = null;
						if ( contentFieldValue.getContentField().getType() == ContentField.LINE_TYPE ) {
							value = contentFieldValue.getSimpleValue();
						} else {
							byte[] valueBytes = contentFieldValue.getValue();
							value = ConvertUtil.convertToString(valueBytes);
						}
						value = StringUtil.elToBr(StringUtil.htmlEncode(value));
						values.put(contentFieldValue.getId(), value);
					} else {
						byte[] value = contentFieldValue.getValue();
						values.put(contentFieldValue.getId(), ConvertUtil.convertToString(value));
					}
				}
			}
		}

		if ( contentFieldValues == null || contentFieldValues.isEmpty() ) {
			// not content field value found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			String localeString = ConvertUtil.convertListToString(cfvLocales, ", ");
			errors.add("contentFieldValueNotFound", new ActionMessage("core.contentFieldValue.errors.notFound", localeString));
			saveErrors(request, errors);
			return mapping.findForward("listContentFieldValues");
		}

		request.setAttribute("contentFieldValues", contentFieldValues);
		request.setAttribute(WebappConstants.CONTENT_FIELD_VALUE_KEY, values);

		// get information about owner
		String ownerInfo = WebappUtil.getLocalizableInfo(contentField.getOwner(), request);
		request.getSession().setAttribute(WebappConstants.OWNER_INFO_KEY, ownerInfo);

		return mapping.findForward("viewContentFieldValue");
	}
}